package com.gegong.vmware.workstation.service;

import com.gegong.vmware.workstation.exceptions.RestApiAccessException;
import com.gegong.vmware.workstation.RestResponse;
import com.gegong.vmware.workstation.VMwareWorkstationManagementActions;
import com.gegong.vmware.workstation.exceptions.VMwareWorkstationManagementException;
import com.google.common.collect.ImmutableMap;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.gegong.vmware.workstation.VMwareWorkstationManagementProperties.*;

public interface VMwareWorkstationManagementService {

    OkHttpClient client = new OkHttpClient().newBuilder()
            .callTimeout(0, TimeUnit.SECONDS)
            .readTimeout(0, TimeUnit.SECONDS)
            .build();

    MediaType defaultPostMediaType = MediaType.parse("application/vnd.vmware.vmw.rest-v1+json");

    Headers defaultHeaders = Headers.of(
            ImmutableMap.<String, String>builder().
                    put("Authorization", "Basic " + new BASE64Encoder().encode(String.format("%s:%s", username, password).getBytes()))
                    .put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36")
                    .build()
    );

    Headers defaultPostHeaders = defaultHeaders.newBuilder().add("Content-Type", "application/vnd.vmware.vmw.rest-v1+json").build();


    default OkHttpClient getHttpClient() {
        return client;
    }


    default String getUrl(VMwareWorkstationManagementActions.BaseAction action, String... params) {
        return restApiRootUrl + String.format(action.getUri(), params);

    }


    default RestResponse getResponse(Request request, VMwareWorkstationManagementActions.BaseAction action) throws VMwareWorkstationManagementException {

        try {
            return new RestResponse(action, client.newCall(request).execute());
        } catch (IOException | AssertionError e) {
            throw new RestApiAccessException(action, e);
        }
    }

}
